package cn.geminis.devops.jenkins

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

def build() {
    def namespace = env.IMAGE_NAMESPACE;
    if (namespace == null) {
        namespace = "k8s.io";
    }
    def name_latest = env.REPOSITORY_URL_DOCKER + env.IMAGE_NAME + ':latest';

    sh """nerdctl -n ${namespace} build --buildkit-host ${env.BUILDKIT_HOST} -t ${name_latest} ./"""
}

@NonCPS
def publish() {
    def formatter = DateTimeFormatter.ofPattern("YYYYMMddHHmmss", Locale.CHINA);
    def version = LocalDateTime.now().format(formatter);
    def namespace = env.IMAGE_NAMESPACE;
    if (namespace == null) {
        namespace = "k8s.io";
    }
    def name_latest = env.REPOSITORY_URL_DOCKER + env.IMAGE_NAME + ':latest';
    def name_version = env.REPOSITORY_URL_DOCKER + env.IMAGE_NAME + ':' + version;

    sh """
        nerdctl tag ${name_latest} ${name_version} --namespace ${namespace}
        nerdctl login --insecure-registry -u ${env.REPOSITORY_USERNAME} -p ${env.REPOSITORY_PASSWORD} ${env.REPOSITORY_URL_DOCKER}
        nerdctl push  --insecure-registry ${name_latest} --namespace ${namespace}
        nerdctl push  --insecure-registry ${name_version} --namespace ${namespace}
        nerdctl rmi ${name_latest} --namespace ${namespace}
        nerdctl rmi ${name_version} --namespace ${namespace}
    """
}

def deploy() {
    sh """kubectl rollout restart deploy ${env.DEPLOY_NAME} -n ${env.DEPLOY_NAMESPACE}"""
}